package com.sun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.reggie.Exception.CustomException;
import com.sun.reggie.common.BaseContext;
import com.sun.reggie.common.R;
import com.sun.reggie.entity.Orders;
import com.sun.reggie.service.OrderDetailService;
import com.sun.reggie.service.OrderService;
import com.sun.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    ShoppingCartService shoppingCartService;


    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/page")
    public R<Page<Orders>> page(Integer page, Integer pageSize, String number, String beginTime, String endTime) {

        Page<Orders> orderspage = new Page<Orders>(page, pageSize);

        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.like(number != null, Orders::getNumber, number);

        ordersLambdaQueryWrapper.between(beginTime != null, Orders::getOrderTime, beginTime, endTime);

        orderService.page(orderspage, ordersLambdaQueryWrapper);

        return R.success(orderspage);
    }

    @PutMapping
    public R<String> deliver(@RequestBody Orders orders){

        Orders order = orderService.getById(orders);
        order.setStatus(orders.getStatus());
        orderService.updateById(order);
        return R.success("修改成功");
    }


    @GetMapping("/userPage")
    public R<Page<Orders>> userPage(Integer page, Integer pageSize) {

        Long userId = BaseContext.getCurrentId();

        if(userId==null){
            throw new CustomException("不存在用户");
        }

        Page<Orders> orderspage = new Page<Orders>(page, pageSize);

        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();

        ordersLambdaQueryWrapper.eq(Orders::getUserId,userId);

        orderService.page(orderspage, ordersLambdaQueryWrapper);

        return R.success(orderspage);
    }

    /**
     * 再来一单
     * @param order
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders order) {
        orderService.again(order);
        return R.success("再来一单啊");
    }


}